/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.admin.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.common.core.encrypt.RSAUtil;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.admin.api.entity.SysLicence;
import com.fuyao.cloud.admin.service.SysLicenceService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

/**
 * 许可证管理表
 *
 * @author liyue
 * @date 2022-11-01 10:38:32
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/syslicence")
@Api(value = "syslicence", tags = "许可证管理表管理")
public class SysLicenceController {

    private final SysLicenceService sysLicenceService;

    /**
     * 分页查询
     *
     * @param page       分页对象
     * @param sysLicence 许可证管理表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('admin_syslicence_view')")
    public R getSysLicencePage(Page page, SysLicence sysLicence) {
        return R.ok(sysLicenceService.page(page, Wrappers.query(sysLicence)));
    }


    /**
     * 通过id查询许可证管理表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('admin_syslicence_view')")
    public R getById(@PathVariable("id") Long id) {
        return R.ok(sysLicenceService.getById(id));
    }

    /**
     * 新增许可证管理表
     *
     * @param sysLicence 许可证管理表
     * @return R
     */
    @ApiOperation(value = "新增许可证管理表", notes = "新增许可证管理表")
    @SysLog("新增许可证管理表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('admin_syslicence_add')")
    public R save(@RequestBody SysLicence sysLicence) {
        return R.ok(sysLicenceService.save(sysLicence));
    }

    /**
     * 修改许可证管理表
     *
     * @param sysLicence 许可证管理表
     * @return R
     */
    @ApiOperation(value = "修改许可证管理表", notes = "修改许可证管理表")
    @SysLog("修改许可证管理表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin_syslicence_edit')")
    public R updateById(@RequestBody SysLicence sysLicence) {
        return R.ok(sysLicenceService.updateById(sysLicence));
    }

    /**
     * 通过id删除许可证管理表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除许可证管理表", notes = "通过id删除许可证管理表")
    @SysLog("通过id删除许可证管理表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('admin_syslicence_del')")
    public R removeById(@PathVariable Long id) {
        return R.ok(sysLicenceService.removeById(id));
    }


    /**
     * 导出excel 表格
     *
     * @param sysLicence 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('admin_syslicence_export')")
    public List<SysLicence> export(SysLicence sysLicence) {
        return sysLicenceService.list(Wrappers.query(sysLicence));
    }

    // 生成许可证
    @SneakyThrows
    @RequestMapping("/generateLicence")
    public void generateLicence(String id, String registerCode, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SysLicence licence = this.sysLicenceService.getById(id);
        Objects.requireNonNull(licence, "未找到相应的许可证。");

        PrivateKey privateKey = RSAUtil.getPrivateKey(licence.getPrivateKey());
        // 这里由于前端将 +转为 " " 这里需要将 " " 转回+ 否则解密失败。
        String decryptString = RSAUtil.decryptString(privateKey, registerCode.replaceAll(" ", "+"));

        log.info("解密 = " + decryptString);
        Objects.requireNonNull(decryptString, "解密失败。");

        List<String> addressList = StrUtil.split(decryptString, ";");
        if(addressList.size() >= 5){
            licence.setCpuId(StrUtil.emptyToDefault(addressList.get(0),StrUtil.EMPTY));
            licence.setMainBoard(StrUtil.emptyToDefault(addressList.get(1),StrUtil.EMPTY));
            licence.setDiskId(StrUtil.emptyToDefault(addressList.get(2),StrUtil.EMPTY));
            licence.setMac(StrUtil.emptyToDefault(addressList.get(3),StrUtil.EMPTY));
            this.sysLicenceService.updateById(licence);
            // licence.setAddress(StrUtil.emptyToDefault(addressList.get(4),StrUtil.EMPTY));
        }

        ClassPathResource classPathResource = new ClassPathResource("licence.lic");
        FileWriter fileWriter = new FileWriter(classPathResource.getFile());
        fileWriter.write("");
        addressList.forEach(s -> {
            fileWriter.append(Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8)) + "\r");
        });
        ClassPathResource resource = new ClassPathResource("licence.lic");
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=licence.lic");
        IoUtil.copy(resource.getInputStream(), response.getOutputStream());
    }
}
